import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function GET() {
  try {
    console.log('开始调试计量单位数据解析...');

    // 从CSV文件解析计量单位数据
    const csvFilePath = path.join(process.cwd(), 'excel/06-21/计量单位定义表.csv');
    
    if (!fs.existsSync(csvFilePath)) {
      return NextResponse.json({ 
        success: false, 
        error: '计量单位定义表.csv 文件不存在' 
      }, { status: 400 });
    }

    const csvContent = fs.readFileSync(csvFilePath, 'utf-8');
    const lines = csvContent.split('\n').filter(line => line.trim());
    
    console.log(`CSV文件总行数: ${lines.length}`);
    
    // 解析CSV数据
    const measurementUnits: Array<{ category: string; unit: string; rowIndex: number; columnPair: number }> = [];
    const debugInfo: Array<{ lineNumber: number; line: string; parsed: Array<{ category: string; unit: string }> }> = [];
    
    // 从第三行开始解析（跳过标题行和列标题行）
    for (let i = 2; i < lines.length; i++) {
      const line = lines[i];
      const columns = line.split(',');
      
      const parsedFromThisLine: Array<{ category: string; unit: string }> = [];
      
      // 每行有8列，每2列为一组 (计量类名, 计量单位)
      for (let j = 0; j < columns.length; j += 2) {
        const category = columns[j]?.trim();
        const unit = columns[j + 1]?.trim();
        
        if (category && unit && category !== '—' && unit !== '—') {
          measurementUnits.push({ 
            category, 
            unit, 
            rowIndex: i + 1, 
            columnPair: Math.floor(j / 2) + 1 
          });
          parsedFromThisLine.push({ category, unit });
        }
      }
      
      debugInfo.push({
        lineNumber: i + 1,
        line: line,
        parsed: parsedFromThisLine
      });
    }

    // 统计信息
    const categoryCount: Record<string, number> = {};
    measurementUnits.forEach(unit => {
      categoryCount[unit.category] = (categoryCount[unit.category] || 0) + 1;
    });

    const duplicateCategories = Object.entries(categoryCount)
      .filter(([category, count]) => count > 1)
      .map(([category, count]) => ({ category, count }));

    return NextResponse.json({
      success: true,
      summary: {
        totalLines: lines.length,
        dataLines: lines.length - 2, // 减去标题行和列头行
        totalParsedUnits: measurementUnits.length,
        duplicateCategories,
        uniqueCategories: Object.keys(categoryCount).length
      },
      debugInfo: debugInfo.slice(0, 10), // 只显示前10行调试信息
      measurementUnits: measurementUnits.slice(0, 20), // 只显示前20个单位
      duplicates: duplicateCategories
    });

  } catch (error) {
    console.error('调试计量单位数据失败:', error);
    return NextResponse.json({
      success: false,
      error: '调试失败: ' + (error as Error).message
    }, { status: 500 });
  }
} 